<template>
  <base-page-view class-name="tab-container order-list">
    <!-- <view class="order-list"> -->
    <view class="order-nav-container">
      <view class="search-block" @click="handelSearch">
        <search-bar ref="search-bar" placeholder="搜索收件人或电话" background="#F5F5F5" disabled></search-bar>
      </view>
      <scroll-view scroll-x="true" class="tab-nav" :scroll-into-view="itemId" :scroll-with-animation="true">
        <view
          v-for="(item, index) in navItems"
          :id="'item' + index"
          :key="item.label"
          class="nav-item"
          :class="{'active': params.selectedIndex === index}"
          @click="onItemClick(index, item)"
        >{{ item.label }}</view>
      </scroll-view>
    </view>
    <!-- <view> -->
    <base-list-view
      :top="198"
      :load-after-init="true"
      :is-empty="isEmpty"
      :btn-text="btnText"
      empty-type="empty_collect"
      empty-text="暂无相关订单信息"
      @btnClick="handleBtnClick"
      @onPullRefresh="onPullRefresh"
      @onLoadMore="onLoadMore">
      <card-box :order-list="orderListData" :params="params" @setShare="setShare" @showCodePopup="showCodePopup"></card-box>
    </base-list-view>
    <!-- </view> -->
    <!-- </view> -->
    <confirm-popup ref="confirmShare" />
    <!-- 验证码弹窗 -->
    <codePopup ref="codePopup" @again="sendCode" @success="code=>checkCode(code)"/>
    <!-- 交易密码弹窗 -->
    <dealPassword ref="dealPassword" v-if="showDealPassword" @complete="completePassword" @close="closeDealPassword"></dealPassword>
  </base-page-view>
</template>
<script>
import searchBar from '@/components/searchBar/index'
import BaseListView from '@/components/base/base-listview'
import cardBox from './cardBox'
import confirmPopup from '@/components/confirmPopup/index'
import codePopup from '@/components/popup/codePopup'
import dealPassword from '@/components/pay/dealPassword'
import { navigateToMiniProgram, toMpHomePage, pageNavigateBack } from '@/utils/navigateTo'
import { getQueryString } from '@/utils/tools'
import './index.scss'
export default {
  components: {
    searchBar,
    BaseListView,
    cardBox,
    confirmPopup,
    codePopup,
    dealPassword
  },
  data() {
    return {
      btnText: '',
      shareOption: {}, // 分享自定义设置
      inviteBtn: null,
      // navItems: ['全部', '待付款', '待发货', '待收货', '已完成'], // , '退货退款'
      from: 'normal', // normal: 我的订单、box: 箱起我的提货订单
      navItems: [
        { label: '全部', value: 0 },
        { label: '待付款', value: 1 },
        { label: '待分享', value: 11 },
        { label: '待发货', value: 2 },
        { label: '待收货', value: 3 },
        { label: '待评价', value: 4 },
        { label: '已完成', value: 44 }
      ], // , '退货退款'
      listTop: 0,
      orderListData: [],
      selectItem: null,
      order_no: '',
      params: {
        pageSize: 10,
        page: 1,
        search: '',
        box_order_type: '',
        selectedIndex: 0, // 当前选中项的序号 默认全部
        orderStatusVal: 0, // 当前选中项的状态值
        loading: false,
        nomore: false
      },
      mescroll: null,// 加载对象
      payOrderNo:'',//支付单号
      showDealPassword: false,  //交易密码弹窗
    }
  },
  computed: {
    itemId() {
      return 'item' + this.params.selectedIndex
    },
    isEmpty() {
      return this.orderListData.length <= 0
    }
  },
  created() {},
  onLoad(option) {
    this.shareOption = {}
    this.inviteBtn = null
    const type = option.type || 0
    this.from = option.from || 'normal'
    if (option.from === 'box') {
      this.navItems = [
        { label: '全部', value: 0 },
        { label: '待付款', value: 1 },
        { label: '待发货', value: 2 },
        { label: '待收货', value: 3 },
        { label: '待评价', value: 4 },
        { label: '已完成', value: 44 }
      ]
    }
    this.navItems.forEach((item, index) => {
      if (item.value === (type - 0)) {
        this.params.orderStatusVal = item.value
        this.params.orderStatusVal = item.value
        this.params.box_order_type = option.from === 'box' ? 2 : ''
        // if (option.from)
        this.params.selectedIndex = index
      }
    })
  },
  onShareAppMessage(res) {
    return this.$queryShareOption(res, this.shareOption)
  },
  methods: {
    //显示验证码弹窗
    showCodePopup(item){
      this.payOrderNo=item.order_no;
      this.showDealPassword = true
      // this.$refs.codePopup.show();
      this.sendCode();//发送验证码
    },
    closeDealPassword() {
      this.showDealPassword = false
    },
    async getPublicKey() {
      let res = await this.$api.mineApi.tradePasswordGetPublicKey()
      if (res.code === 0) {
        this.publicKey = res.data
      }
    },
    // 交易密码输入完成
    async completePassword(str){
      await this.getPublicKey()
       // 加密, 提交
      let jse = new this.$jsEncrypt()
      jse.setPublicKey(this.publicKey)
      let encrypted = jse.encrypt(str)
      this.checkCode(encrypted)
    },
    //发送验证码
    sendCode(){
      this.$api.orderApi.orderPay({
        pay_channel:11, // pay_channel为9时发送验证码,
        order_no: this.payOrderNo
      }).then(res=>{
        if(res.code==0){
          // this.$msg("验证码发送成功");
          // this.$refs.codePopup.countDown();//验证码倒计时
        }
      })
    },
    //判断验证码是否正确
    checkCode(password){
      this.$api.orderApi.checkVerifyDealPassword({
        password: password, 
        order_no: this.payOrderNo
      }).then(res=>{
        this.showDealPassword = false
        // this.$refs.codePopup.close();//关闭验证码弹窗
        this.resetUp()
        this.$navigateTo('/pagesOrder/orderSuccess/index?orderNo=' + this.payOrderNo)
      }).catch((err)=>{
        // 1000002
        if(err.code === 1000002){
          this.showDealPassword = false
          uni.showToast({
            title: "未设置密码，请先设置",
            icon: 'none',
            duration: 2000
          })
          setTimeout(() => {
            this.$navigateTo("/pagesMine/dealPassword/index")
          }, 2000);
        }else{
          // 清除密码
          this.$refs.dealPassword.clearPassword()
          uni.showToast({
            title: err.msg,
            icon: 'none',
            duration: 3 * 1000
          })
        }
      });
    },
    // 前往搜索
    handelSearch() {
      this.$navigateTo(`/pagesOrder/orderSearch/index?from=${this.from}`)
    },
    // 返回
    handelBack() {
      if (this.extraData && this.extraData.platform) {
        navigateToMiniProgram({
          success: () => {
            toMpHomePage()
            console.log('返回成功')
            this.$store.dispatch('setExtraData', null)
            this.$store.dispatch('setGoodsTemp', null)
          }
        })
      } else {
        pageNavigateBack()
      }
    },
    resetUp() {
      if (this.mescroll) {
        this.initData()
        this.mescroll.resetUpScroll(true)
      }
    },
    // 初始化数据
    initData() {
      this.params.page = 1
      this.params.loading = false
      this.params.nomore = false
    },
    // 转跳到对应的订单状态页
    onItemClick(index, item) {
      this.params.selectedIndex = index
      this.params.orderStatusVal = item.value
      this.initData()
      this.mescroll.resetUpScroll(true)
    },
    setShare(item) {
      console.log('setShare', item)
      this.inviteBtn = item.invite_btn
      this.initShare()
      this.$refs.confirmShare.show({
        title: '提示',
        content: '是否分享给好友',
        authBtn: true,
        yesTxt: '',
        openType: 'share'
      })
    },
    // 获取订单列表
    async _getDataList() {
      // 1:待付款2:待发货3:待收货4:已收货5:已取消6:付款异常7:超时取消8:已退款11:待分享
      const result = await this.$api.orderApi.getOrderList({
        page_size: this.params.pageSize,
        page_no: this.params.page,
        search: this.params.search,
        box_order_type: this.params.box_order_type,
        status: this.navItems[this.params.selectedIndex].value === 0 ? '' : (this.navItems[this.params.selectedIndex].value) === 44 ? 4 : this.navItems[this.params.selectedIndex].value,
        comment_status: this.navItems[this.params.selectedIndex].label === '待评价' ? 1 : ''
      })
      return result
    },
    // 下拉刷新
    async onPullRefresh(mescroll) {
      this.initData()
      this.commonData(mescroll)
    },
    // 上拉加载
    async onLoadMore(mescroll) {
      if (!this.mescroll) this.mescroll = mescroll
      if (this.params.nomore) {
        mescroll.endSuccess(0)
        return
      }
      this.params.page = mescroll.num
      this.commonData(mescroll)
    },
    async commonData(mescroll) {
      const res = await this._getDataList()
      if (res.success) {
        if (this.params.page === 1) {
          this.orderListData = []
        }
        this.orderListData = this.orderListData.concat(res.data)
        if (res.data.length < this.params.pageSize) {
          this.params.nomore = true
        }
        mescroll.endSuccess(this.params.pageSize)
      } else {
        this.orderListData = []
        mescroll.endErr()
      }
    },
    // 去逛逛
    handleBtnClick() {
      this.$navigateTo('/pagesMine/order/index')
    },

    // 分享初始化
    initShare() {
      if (this.inviteBtn && this.inviteBtn.url) {
        let share_url = this.inviteBtn.url
        if (share_url.match('/#/')) {
          const urlArr = share_url.split('/#/')
          share_url = urlArr[1].replace('detail/goods', '/pagesDetail/commodity/index')
        } else {
          const url = getQueryString('path', share_url)
          share_url = decodeURIComponent(url)
          // console.log(share_url, 6666)
        }
        this.shareOption.share_title = this.inviteBtn.title
        this.shareOption.share_url = share_url
        this.shareOption.share_icon = this.inviteBtn.pic
        this.shareOption.share_content = this.inviteBtn.content
        this.showShare()
      } else {
        this.hideShare()
      }
    }
  }
}
</script>
